package com.situ.science.interceptor;


import com.situ.science.pojo.Auth;
import com.situ.science.pojo.Researchers;
import com.situ.science.utils.JwtUtil;
import com.situ.science.utils.ThreadLocalUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        //1.判断用户有没有登录
        //2.如果登录了，就放行，可以访问后台的资源
        //3.如果没有登录，跳转到登录界面
        String token = request.getHeader("Authorization");
        try {
            //验证token
            Map<String, Object> map = JwtUtil.parseToken(token);
            //放行
            ThreadLocalUtil.set(map);
            return true;
        } catch (Exception e) {
            //http响应状态码改为401
            response.setStatus(401);
            //不放行
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
